package com.nw.serviceImpl;

import com.nw.dao.UserDao;
import com.nw.entity.User;
import com.nw.service.UserService;
import com.nw.util.ImageCodeUtil;
import com.nw.util.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    UserDao userDao;

    @Resource
    RedisTemplate redisTemplate;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public HashMap<String, Object> queryByUsername(User user, String enCode) {
        HashMap<String, Object> map = new HashMap<>();
        System.out.println("接受的参数为:"+user);
        System.out.println("接受的验证码为:"+enCode);

        //获取String类型的操作
        HashOperations hashOperations = stringRedisTemplate.opsForHash();
        String redisCode = (String) hashOperations.get("enCode",enCode);



        if (enCode.equals(redisCode)) {
            map.put("0", "验证码正确");
            User userFromDataBase = userDao.queryByUsername(user.getUsername());
            //获取主体对象
            Subject subject = SecurityUtils.getSubject();
            //创建token
            String salt = null;
            try {
                salt = userDao.queryByUsername(user.getUsername()).getSalt();
            } catch (Exception e) {
                salt = null;
            }

            Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
            String md5Password = md5Hash.toHex();
            UsernamePasswordToken token = null;
            token = new UsernamePasswordToken(user.getUsername(), md5Password);
            try {
                //认证
                subject.login(token);
                map.put("token", TokenUtil.getToken(userFromDataBase.getUsername()+userFromDataBase.getPassword()));
                map.put("0", "登陆成功");
                List<User> users = userDao.queryByUsernameLeftJoinLike(user.getUsername());
                map.put("data",users);
            } catch (UnknownAccountException e) {
                System.out.println("用户名不存在，判断手机号是否存在");
                if(userDao.queryByUserPhone(user.getUsername()) != null){
                    String usernameP = userDao.queryByUserPhone(user.getUsername()).getUsername();
                    String saltP = userDao.queryByUserPhone(user.getUsername()).getSalt();
                    String md5PasswordP = new Md5Hash(user.getPassword(),saltP,1024).toHex();
                    //System.out.println(saltP);
                    //System.out.println(md5PasswordP);
                    token = new UsernamePasswordToken(usernameP, md5PasswordP);
                    try {
                        subject.login(token);
                        map.put("token", TokenUtil.getToken(usernameP+md5PasswordP));
                        List<User> userP = userDao.queryByUsernameLeftJoinLike(usernameP);
                        map.put("0", "登陆成功");
                        map.put("data",userP);
                    } catch (IncorrectCredentialsException eP) {
                        map.put("1","密码错误");
                    }
                }else {
                    map.put("1", "用户名不存在");
                }
            } catch (IncorrectCredentialsException e) {
                map.put("1", "密码错误");
            }
        }else {
            map.put("1","验证码错误");
        }

        return map;
    }

    @Override
    public HashMap<String, Object> add(User user) {
        HashMap<String, Object> map = new HashMap<>();
        user.setId(UUID.randomUUID().toString());

        //使用shiro密码术进行加密
        String salt = ImageCodeUtil.getSecurityCode();

        Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
        try {
            System.out.println("前端发送的user整合后为:"+user);
            userDao.add(user);
            map.put("0","用户添加成功");
        } catch (Exception e) {
            //e.printStackTrace();
            map.put("1","用户已存在");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> userExist(String username) {
        User user = userDao.queryByUsername(username);
        HashMap<String, Object> map = new HashMap<>();
        if (user == null) {
            map.put("code","0");
            map.put("nameStatus","1");
        }else {
            map.put("code","0");
            map.put("nameStatus","0");
        }
        return map;
    }

    @Override
    public List<User> queryByUsernameLeftJoinLike(String username) {
        return null;
    }

    /**/
}
